﻿Imports System.Xml
Imports System.IO
Imports System.Net.Mail
Imports System.Net

Public Class Form1
    Public adddelay As String = "N"
    Public wait As Integer = 180
    Public AutoClose As String = "N"
    'AddDelay = N/Y"
    Public Start As String
    Dim CanClose As Boolean = False
    Public CheckForMissing = "N"
    Public ExtractWait As Integer = 3000
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            If Now.Day = 7 Then
                If File.Exists(My.Application.Info.DirectoryPath & "\logs.txt") Then
                    File.Delete(My.Application.Info.DirectoryPath & "\logs.txt")
                End If
            End If
            File.Delete(My.Application.Info.DirectoryPath & "\FileSendingVERIFY.txt")
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try
        Try

            Me.Text = Me.Text & " v" & My.Application.Info.Version.ToString
            CheckForIllegalCrossThreadCalls = False
            'Read Settings from Xml
            Dim xr As XmlTextReader = New XmlTextReader(My.Application.Info.DirectoryPath & "\Settings.xml")
            Do While xr.Read()
                If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "store" Then
                    lblstore.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "storeemail" Then
                    lblemail.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "sharepath" Then
                    txtsharepath.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftp" Then
                    txtftp.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftpuser" Then
                    txtftpuser.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftppass" Then
                    txtftppass.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "smtp" Then
                    txtsmtp.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "smtpport" Then
                    txtsmptport.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "smtpuser" Then
                    txtsmtpuser.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "smtppass" Then
                    txtsmptpass.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "bootdrv" Then
                    lblbootdrv.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftp2" Then
                    txtftp2.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftpuser2" Then
                    txtfrtuser2.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftppass2" Then
                    txtftppassword2.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "DateWillBeSend" Then
                    'Add Data Grid
                    'DataGridView1.Rows.Add(xr.ReadElementString)

                    'Get Date Today
                    Dim Today As String
                    If Now.Hour <= 10 Then
                        Today = Now.AddDays(-1).ToString("yyyyMMdd")
                    Else
                        Today = Now.ToString("yyyyMMdd")
                    End If
                    DataGridView1.Rows.Add(Today)
                Else
                    xr.Read()
                End If

            Loop
            'Read Arguments

        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try
        Dim CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.CommandLineArgs
        For i As Integer = 0 To CommandLineArgs.Count - 1
            'MessageBox.Show(CommandLineArgs(i))
            If CommandLineArgs(i).Contains("AddDelay") Then
                adddelay = CommandLineArgs(i + 1)
            ElseIf CommandLineArgs(i).Contains("wait") Then
                wait = CommandLineArgs(i + 1)
            ElseIf CommandLineArgs(i).Contains("AutoClose") Then
                AutoClose = CommandLineArgs(i + 1)
            ElseIf CommandLineArgs(i).Contains("CheckMissing") Then
                CheckForMissing = CommandLineArgs(i + 1)
            ElseIf CommandLineArgs(i).Contains("ExtractWait") Then
                CheckForMissing = CommandLineArgs(i + 1)
            ElseIf CommandLineArgs(i).Contains("help") Then
                MsgBox("Arguments -adddelay(Y/N) -wait(seconds) -AutoClose (Y/N) -CheckMissing (Y/) -ExtractWait (milliseconds)", vbInformation, "Help")
            End If
        Next
        ' MsgBox(wait)

        If adddelay = "Y" Then
            Timer2.Interval = 1000
            Timer2.Enabled = True
        End If
        If CheckForMissing = "Y" Then
            CheckMissingThread.Start()
        End If
        CanClose = False

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            If adddelay = "Y" Then
                Dim a = MsgBox("Are you sure you want to Override Automatic Dated Folder Sending?", vbYesNoCancel)
                If a = MsgBoxResult.Yes Then
                    Timer2.Enabled = False
                    TreadingSend.Abort()
                    GoTo Manual
                End If
            Else
Manual:
                ManualSending.Abort()

                ManualSending = New Threading.Thread(AddressOf SendThread)
                ManualSending.Start()
            End If
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try
       
    End Sub
#Region "Threads"
    Dim TreadingSend As New Threading.Thread(AddressOf SendThread)
    Dim ManualSending As New Threading.Thread(AddressOf SendThread)
    Dim CheckMissingThread As New Threading.Thread(AddressOf CheckMissingDatedFolderT)
    Sub SendThread()
        Try
            For Each rows As DataGridViewRow In DataGridView1.Rows
                If (rows.Cells(0).Value <> "") Then
                    If File.Exists(lblbootdrv.Text & rows.Cells(0).Value & ".rar") Then
                        File.Delete(lblbootdrv.Text & rows.Cells(0).Value & ".rar")
                    End If
                    WriteTable(rows.Index, "Archiving..")
                    WriteStatus("Archiving " & rows.Cells(0).Value & ".rar")
                    WriteLogs("Archiving " & rows.Cells(0).Value & ".rar")
                    'InputBox("a", "a", "C:\Program Files\WinRAR\rar.exe a -ep " & lblbootdrv.Text & rows.Cells(0).Value & ".rar " & lblbootdrv.Text & rows.Cells(0).Value & rows.Cells(0).Value)
                    'MsgBox("C:\Program Files\WinRAR\rar.exe a -ep " & lblbootdrv.Text & rows.Cells(0).Value & ".rar " & lblbootdrv.Text & rows.Cells(0).Value)
                    SyncLock Me
                        'Shell("C:\Program Files\WinRAR\rar.exe a -ep " & lblbootdrv.Text & rows.Cells(0).Value & ".rar " & lblbootdrv.Text & rows.Cells(0).Value, AppWinStyle.MinimizedNoFocus, True)
                        Process1.StartInfo.Arguments = "a -ep " & lblbootdrv.Text & rows.Cells(0).Value.ToString & ".rar " & lblbootdrv.Text & rows.Cells(0).Value.ToString
                        Process1.Start()
                        Process1.WaitForExit()
                    End SyncLock

                    'Threading.Thread.Sleep(ExtractWait)

                    If File.Exists(lblbootdrv.Text & rows.Cells(0).Value & ".rar") Then

                        ' GoTo Email
                        WriteTable(rows.Index, "Sending..")
                        WriteStatus("Sending " & rows.Cells(0).Value & ".rar")
                        WriteLogs("Sending " & rows.Cells(0).Value & ".rar")

                        If NetworkWithProgress(lblbootdrv.Text, rows.Cells(0).Value & ".rar") = True Then
                            'End

                            WriteTable(rows.Index, "Done")
                            WriteStatus("Done Sending " & rows.Cells(0).Value & ".rar")
                            WriteLogs("Done Sending " & rows.Cells(0).Value & ".rar")
                            ProgressStatus(0)
                            WriteLastResults("SUCCESS : " & rows.Cells(0).Value & " ", True)
                        Else
FTP:
                            'Remove Any Incomplete Data
                            'If File.Exists(lblbootdrv.Text & rows.Cells(0).Value & ".rar") Then
                            '    File.Delete(lblbootdrv.Text & rows.Cells(0).Value & ".rar")
                            'End If

                            WriteTable(rows.Index, "Sending via FTP")
                            WriteStatus("Sending via FTP " & rows.Cells(0).Value & ".rar")
                            WriteLogs("Sending via FTP " & rows.Cells(0).Value & ".rar")
                            ToolStripProgressBar1.ProgressBar.Value = 0
                            If Ftp(lblbootdrv.Text, rows.Cells(0).Value & ".rar") = True Then
                                WriteTable(rows.Index, "Done")
                                WriteStatus("Done Sending " & rows.Cells(0).Value & ".rar")
                                WriteLogs("Done Sending " & rows.Cells(0).Value & ".rar")
                                WriteLastResults("SUCCESS : " & rows.Cells(0).Value & " ", True)
                            Else
FTP2:
                                WriteTable(rows.Index, "Sending via FTP2")
                                WriteStatus("Sending via FTP2 " & rows.Cells(0).Value & ".rar")
                                WriteLogs("Sending via FTP2 " & rows.Cells(0).Value & ".rar")
                                ToolStripProgressBar1.ProgressBar.Value = 0
                                If Ftp2(lblbootdrv.Text, rows.Cells(0).Value & ".rar") = True Then
                                    WriteTable(rows.Index, "Done")
                                    WriteStatus("Done Sending " & rows.Cells(0).Value & ".rar")
                                    WriteLogs("Done Sending " & rows.Cells(0).Value & ".rar")
                                    WriteLastResults("SUCCESS : " & rows.Cells(0).Value & " ", True)
                                Else
Email:
                                    WriteLastResults("FAILED : [DATE] " & rows.Cells(0).Value & " because Unable to connect to HO File Server", False)
                                    WriteTable(rows.Index, "Sending via Email")
                                    WriteStatus("Sending via Email " & rows.Cells(0).Value & ".rar")
                                    WriteLogs("Sending via Email " & rows.Cells(0).Value & ".rar")
                                    ProgressStatus(0)
                                    If EMail(lblbootdrv.Text, rows.Cells(0).Value & ".rar") = True Then
                                        WriteTable(rows.Index, "Done")
                                        WriteStatus("Done Sending " & rows.Cells(0).Value & ".rar")
                                        WriteLogs("Done Sending " & rows.Cells(0).Value & ".rar")
                                    Else
                                        WriteTable(rows.Index, "Failed")
                                        WriteStatus("Sending Failed " & rows.Cells(0).Value & ".rar")
                                        WriteLogs("Sending Failed " & rows.Cells(0).Value & ".rar")

                                        'Error
                                        WriteLastResults("FAILED : [DATE] " & rows.Cells(0).Value & " because Unable to connect to HO File Server", False)
                                    End If
                                End If
                            End If

                        End If

                    Else
                        WriteTable(rows.Index, "File Doesn't Exist")
                        WriteStatus("File Doesn't Exist " & rows.Cells(0).Value & ".rar")
                        WriteStatus("File Doesn't Exist " & rows.Cells(0).Value & ".rar")
                    End If

                End If
                ProgressStatus(0)
            Next
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try
        ProgressStatus(0)

        SaveLogs("Done")
        Timer2.Enabled = False
        CanClose = True
        If AutoClose = "Y" Then
            'Show Message
            Try
                Dim FILE_NAME As String = My.Application.Info.DirectoryPath & "\FileSendingVERIFY.txt"
                Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
                objWriter.WriteLine(" ")
                objWriter.WriteLine(" ")
                objWriter.WriteLine(" ")
                objWriter.WriteLine("Please EMAIL [Failed-to-send] Dated Folder Compressed file(s) urgently to MIS@roasters.com.ph")
                objWriter.WriteLine("try to help MIS Department by sending the Dated Folder")
                objWriter.WriteLine("It would benefit us all!")
                objWriter.WriteLine("Thank you very much!")
                objWriter.WriteLine("-MIS Team")

                objWriter.Close()
                System.Diagnostics.Process.Start("notepad.exe", My.Application.Info.DirectoryPath & "\FileSendingVERIFY.txt")

                WriteLogs("****************VERIFY EXECUTED****************")
            Catch ex As Exception
            End Try
            End
        End If
    End Sub
    Sub CheckMissingDatedFolderT()
        Try

       
        Dim ConnectionMethodMode As Integer = 0
        Dim CheckForComplete As Boolean
        If CheckConnectionviaSharing() = True Then
            ConnectionMethodMode = 1
            CheckForComplete = True
        Else
            If CheckConnectionviaFTP() = True Then
                ConnectionMethodMode = 2
                CheckForComplete = True
            Else
                CheckForComplete = False
                'Do Not Check data Completeness
            End If
        End If
        'ConnectionMethodMode = 2
        'List Date
        If CheckForComplete = True Then
            Dim DateNow As Integer = Now.Day - 1

            Dim RawDate As String

            For value As Integer = 2 To DateNow
                RawDate = Now.AddDays(-value).ToString("yyyyMMdd")
                WriteLogs("Checking Uploaded Dated Folders.." & RawDate & " in Mode [" & ConnectionMethodMode.ToString & "].")
                WriteStatus("Checking Uploaded Dated Folders.." & RawDate)
                If ConnectionMethodMode = 1 Then
                    If (CheckFileExistSharing(RawDate)) = False Then
                        'Add To List
                            DataGridView1.Rows.Add(RawDate)
                            DataGridView1.Refresh()
                    End If
                ElseIf ConnectionMethodMode = 2 Then
                    If CheckFileExistFTP(RawDate) = False Then
                            DataGridView1.Rows.Add(RawDate)
                            DataGridView1.Refresh()
                    End If
                End If
            Next
        Else
            WriteStatus("Checking Missing Dated Folder Cancelled")
            WriteLogs("Checking Missing Dated Folder Cancelled")
        End If
        WriteStatus("Checking Missing Dated Folder Done.")
            WriteLogs("Checking Missing Dated Folder Done.")
        Catch ex As Exception
            WriteStatus("Checking Missing Dated Folder Done.")
            WriteLogs("Checking Missing Dated Folder Done With Error : " & ex.Message)
        End Try
    End Sub

#End Region
#Region "Main Functions"
    Public Sub SaveBinaryFile(strFilename As String, bytesToWrite() As Byte)
        Dim position As Integer = 0
        Dim BufferSize As Integer = 4096
        ToolStripProgressBar1.ProgressBar.Value = 0

        Using fsNew As FileStream = New FileStream(strFilename, FileMode.Create, FileAccess.Write)
            Do
                Dim intToCopy As Integer = Math.Min(BufferSize, bytesToWrite.Length - position)
                Dim buffer(intToCopy - 1) As Byte
                Array.Copy(bytesToWrite, position, buffer, 0, intToCopy)
                fsNew.Write(buffer, 0, buffer.Length)
                ProgressStatus(((position / bytesToWrite.Length) * 100), "Sending ")
                Application.DoEvents()
                position += intToCopy
            Loop While position < bytesToWrite.Length
        End Using
    End Sub
    Public Function ReadBinaryFile(strFilename As String) As Byte()
        Dim position As Integer = 0
        Dim bufferSize As Integer = 4096
        Dim bytes() As Byte
        ToolStripProgressBar1.ProgressBar.Value = 0

        Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open)
            ReDim bytes((fsOpen.Length) - 1)
            Do
                If (position + bufferSize) > fsOpen.Length Then
                    fsOpen.Read(bytes, position, fsOpen.Length - position)
                    Exit Do
                Else
                    fsOpen.Read(bytes, position, bufferSize)
                End If
                ProgressStatus(((position / fsOpen.Length) * 100), "Analyzing ")
                Application.DoEvents()
                position += bufferSize
            Loop
        End Using

        Return bytes

    End Function
    Function Network(path As String, filename As String) As Boolean
        If File.Exists(txtsharepath.Text & lblstore.Text & "\" & filename) = False Then
            File.Copy(path & filename, txtsharepath.Text & lblstore.Text & "\" & filename, True)
        End If
        If File.Exists(txtsharepath.Text & lblstore.Text & "\" & filename) Then
            Return True
        End If
        Return False
    End Function
    Function NetworkWithProgress(path As String, filename As String) As Boolean
        Try
            If File.Exists(txtsharepath.Text & lblstore.Text & "\" & filename) = False Then
                SyncLock Me
                    SaveBinaryFile(txtsharepath.Text & lblstore.Text & "\" & filename, ReadBinaryFile(path & filename))
                End SyncLock
            End If
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try

        If File.Exists(txtsharepath.Text & lblstore.Text & "\" & filename) Then
            Return True
        End If
        Return False
    End Function
    Function Ftp(path As String, filename As String) As Boolean
        Try
            Dim convert As String = txtftp.Text & lblstore.Text & "\" & filename
            convert = convert.Replace("\", "/")
            ' MsgBox(convert)

            Dim clsRequest As System.Net.FtpWebRequest = _
            DirectCast(System.Net.WebRequest.Create(convert), System.Net.FtpWebRequest)
            clsRequest.Credentials = New System.Net.NetworkCredential(txtftpuser.Text, txtftppass.Text)
            clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
            clsRequest.Proxy = Nothing
            'MsgBox(convert)
            Dim bFile() As Byte = System.IO.File.ReadAllBytes(path & filename)

            ' upload file...
            Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
            SyncLock Me
                For offset As Integer = 0 To bFile.Length Step 1024
                    ProgressStatus(CType(offset * 100 / bFile.Length, Integer), "Sending :")
                    Dim chunkSize As Integer = bFile.Length - offset
                    If chunkSize > 1024 Then chunkSize = 1024
                    clsStream.Write(bFile, offset, chunkSize)
                Next
                clsStream.Close()
                clsStream.Dispose()
            End SyncLock
            Return True
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try
        Return False
    End Function
    Function Ftp2(path As String, filename As String) As Boolean
        Try
            Dim convert As String = txtftp2.Text & lblstore.Text & "\" & filename
            convert = convert.Replace("\", "/")
            ' MsgBox(convert)

            Dim clsRequest As System.Net.FtpWebRequest = _
            DirectCast(System.Net.WebRequest.Create(convert), System.Net.FtpWebRequest)
            clsRequest.Credentials = New System.Net.NetworkCredential(txtfrtuser2.Text, txtftppassword2.Text)
            clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
            clsRequest.Proxy = Nothing
            'MsgBox(convert)
            Dim bFile() As Byte = System.IO.File.ReadAllBytes(path & filename)

            ' upload file...
            Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
            SyncLock Me
                For offset As Integer = 0 To bFile.Length Step 1024
                    ProgressStatus(CType(offset * 100 / bFile.Length, Integer), "Sending :")
                    Dim chunkSize As Integer = bFile.Length - offset
                    If chunkSize > 1024 Then chunkSize = 1024
                    clsStream.Write(bFile, offset, chunkSize)
                Next
                clsStream.Close()
                clsStream.Dispose()
            End SyncLock
            Return True
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try
        Return False
    End Function
    Function EMail(path As String, filename As String) As Boolean
        Dim mail As New MailMessage
        Try
            ProgressStatus(10)
            mail.Subject = "EOD-" & lblstore.Text
            mail.To.Add("loisrosas@roasters.com.ph")
            mail.From = New MailAddress(lblemail.Text)
            mail.Body = "Auto-Email"
            Dim Myattachment As System.Net.Mail.Attachment
            Myattachment = New System.Net.Mail.Attachment(path & filename)
            ProgressStatus(50)
            mail.Attachments.Add(Myattachment)



            Dim SMTP As New SmtpClient(txtsmtp.Text)
            SMTP.EnableSsl = False
            SMTP.Credentials = New System.Net.NetworkCredential(txtsmtpuser.Text, txtsmptpass.Text)
            SMTP.Port = Integer.Parse(txtsmptport.Text)
            ProgressStatus(70)
            'SMTP.
            ' WebRequest.DefaultWebProxy = New WebProxy("192.168.10.5", 3128)
            'SMTP.UseDefaultCredentials = True
            SMTP.Send(mail)
            ProgressStatus(100)
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
            ProgressStatus(0)
            Return False
        End Try
        Return True
    End Function


    Function CheckFileExistSharing(Datetarget As String) As Boolean
        WriteStatus("Looking for " & Datetarget)
        If File.Exists(txtsharepath.Text & lblstore.Text & "\" & Datetarget & ".rar") Then
            WriteStatus("Looking for " & Datetarget & " Found!")
            Return True
        Else
            WriteStatus("Looking for " & Datetarget & "Not Found!")
            Return False
        End If
    End Function
    Function CheckFileExistFTP(Datetarget As String) As Boolean
        WriteStatus("FTP : Looking for " & Datetarget)
        Dim request As FtpWebRequest = WebRequest.Create(txtftp.Text & lblstore.Text & "/" & Datetarget & ".rar")
        request.Credentials = New NetworkCredential(txtftpuser.Text, txtftppass.Text)
        request.Method = WebRequestMethods.Ftp.GetFileSize
        request.Proxy = Nothing

        Try
            Dim response As FtpWebResponse = request.GetResponse()

            Return True
            ' THE FILE EXISTS
        Catch ex As WebException
            Dim response As FtpWebResponse = ex.Response
            If FtpStatusCode.ActionNotTakenFileUnavailable = response.StatusCode Then
                ' THE FILE DOES NOT EXIST
                Return False
            End If
        End Try
        Return True
    End Function

    Function CheckConnectionviaSharing() As Boolean
        WriteStatus("Checking Network Connection...")
        WriteLogs("Checking Network Connection...")
        If My.Computer.Network.IsAvailable Then
            WriteStatus("Checking Network Connection...Ok")
            WriteLogs("Checking Network Connection...Ok")
        Else
            WriteStatus("Checking Your Network Connection.")
            WriteLogs("Checking Your Network Connection.")
        End If

        WriteStatus("Checking Head Office Connectivity...")
        WriteLogs("Checking Head Office Connectivity...")

        If Directory.Exists(txtsharepath.Text) Then
            WriteStatus("Connected to Head Office")
            WriteLogs("Connected to Head Office")
            Return True
        Else
            WriteStatus("Cannot Connect to Head Office Check Your Connection")
            WriteLogs("Cannot Connect to Head Office Check Your Connection")
            Return False
        End If
        WriteStatus("Cannot Connect to Head Office Check Your Connection")
        WriteLogs("Cannot Connect to Head Office Check Your Connection")
        Return False
    End Function
    Function CheckConnectionviaFTP() As Boolean
        WriteStatus("Checking Network Connection...")
        WriteLogs("Checking Network Connection...")
        If My.Computer.Network.IsAvailable Then
            WriteStatus("Checking Network Connection...Ok")
            WriteLogs("Checking Network Connection...Ok")
        Else
            WriteStatus("Checking Your Network Connection.")
            WriteLogs("Checking Your Network Connection.")
        End If

        WriteStatus("FTP : Checking Head Office Connectivity...")
        WriteLogs("FTP : Checking Head Office Connectivity...")

        Dim request = _
        DirectCast(WebRequest.Create(txtftp.Text), FtpWebRequest)

        request.Credentials = _
        New NetworkCredential(txtftpuser.Text, txtftppass.Text)

        request.Method = WebRequestMethods.Ftp.ListDirectory

        Try
            Using response As FtpWebResponse = _
            DirectCast(request.GetResponse(), FtpWebResponse)
                ' Folder exists here
                WriteStatus("FTP : Connected to Head Office")
                WriteLogs("FTP : Connected to Head Office")
                Return True
            End Using

        Catch ex As WebException
            Dim response As FtpWebResponse = _
            DirectCast(ex.Response, FtpWebResponse)
            'Does not exist
            WriteStatus(ex.Message)
            WriteLogs("FTP : Cannot Connect to Head Office Because : " & ex.Message)
            If response.StatusCode = _
            FtpStatusCode.ActionNotTakenFileUnavailable Then
                Return False
            End If
        End Try
        Return False
    End Function
#End Region
#Region "Logs"
    Sub WriteTable(index As Integer, Message As String)
        Try
            DataGridView1.Rows(index).Cells(1).Value = Message
        Catch ex As Exception

        End Try
    End Sub
    Sub WriteStatus(Message As String)
        ToolStripStatusLabel1.Text = Message
    End Sub
    Sub WriteLogs(Message As String)
        TextBox1.AppendText(Now & " : " & Message & vbCrLf)
        SaveLogs(Now & " : " & Message)
    End Sub
    Sub WriteLastResults(MessageLine As String, success As Boolean)
        Try
            Dim FILE_NAME As String = My.Application.Info.DirectoryPath & "\FileSendingVERIFY.txt"
            Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
            objWriter.WriteLine(MessageLine)

            'Please send [Failed-to-send] file(s) urgently to MIS@roasters.com.ph 
            'try to help MIS Dept by sending the Dated Folder
            'It would benefit us all!
            'Thank you very much!

            objWriter.Close()
        Catch ex As Exception
            WriteStatus(ex.Message)
        End Try
    End Sub
    Sub SaveLogs(MessageLine)
        Try
            Dim FILE_NAME As String = My.Application.Info.DirectoryPath & "\logs.txt"
            Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
            'For Each line In TextBox1.Lines
            '    objWriter.WriteLine(line)
            'Next
            objWriter.WriteLine(MessageLine)
            objWriter.Close()
            'WriteStatus("Done")
        Catch ex As Exception
            WriteStatus(ex.Message)
        End Try
    End Sub
    Sub ProgressStatus(val As Integer, Optional ByVal Msg As String = "")
        Try
            ToolStripProgressBar1.ProgressBar.Value = val
            ToolStripProgressBar1.ProgressBar.Refresh()
            If val <> 0 Then
                WriteLogs(Msg & " " & val & "%")
            End If
        Catch ex As Exception

        End Try
    End Sub

#End Region


    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        ' wait = wait + 1
        If wait > 0 Then
            WriteStatus("Sending in (" & wait.ToString & ") secs")
            wait -= 1
        Else
            ' TreadingSend()
            TreadingSend.Start()
            Timer2.Enabled = False
        End If
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        WriteLogs(e.CloseReason.ToString)

        If CanClose = False Then
            e.Cancel = True
            Return
        End If
        

    End Sub



    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim a = MsgBox("Are you sure you want to check manually?", vbYesNoCancel)
        If a = MsgBoxResult.Yes Then
            CheckMissingThread.Abort()

            CheckMissingThread = New Threading.Thread(AddressOf CheckMissingDatedFolderT)
            CheckMissingThread.Start()
        End If
    End Sub
    
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim testmailb As Boolean
        testmailb = TestMail()
        WriteStatus("Testing Mail : " & testmailb)
        WriteLogs("Testing Mail : " & testmailb)
        CanClose = True
    End Sub

    Function TestMail() As Boolean
        WriteStatus("Testing Mail...")
        WriteLogs("Testing Mail...")
        Dim mail As New MailMessage
        Try
            ProgressStatus(10)
            WriteStatus("Setting Up Mail..")
            WriteLogs("Setting Up Mail..")
            mail.Subject = "[Test Mail]-" & lblstore.Text
            mail.To.Add("loisrosas@roasters.com.ph")
            mail.From = New MailAddress(lblemail.Text)
            mail.Body = "Test-Email"
            ProgressStatus(50)
            WriteStatus("Configuring Credentials...")
            WriteLogs("Configuring Credentials...")
            'SMTP.Credentials = New System.Net.NetworkCredential(txtsmtpuser.Text, txtsmptpass.Text)

            Dim SMTP As New SmtpClient()
            SMTP.EnableSsl = CheckBox1.Checked
            SMTP.Host = txtsmtp.Text
            SMTP.Port = Integer.Parse(txtsmptport.Text)
            SMTP.UseDefaultCredentials = True

            Dim basicAuthenticationInfo As New System.Net.NetworkCredential(txtsmtpuser.Text, txtsmptpass.Text)
            SMTP.Credentials = basicAuthenticationInfo
            
            SMTP.DeliveryMethod = SmtpDeliveryMethod.Network
            ProgressStatus(70)
            'SMTP.
            WebRequest.DefaultWebProxy = New WebProxy("192.168.1.230", 3128)

            WriteStatus("Sending Test Mail")
            WriteLogs("Sending Test Mail")
            SMTP.Send(mail)
            ProgressStatus(100)
            MsgBox(SMTP.ToString())

        Catch ex As Exception
            MsgBox(ex.Message)
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
            ProgressStatus(0)
            Return False
        End Try
        Return True
    End Function



End Class
